<template>
	<view class="mask" @touchmove.stop.prevent @click="cancel">
		<view class="time_select" @click.stop="">
			<view class="time_select-head">
				<view @click="closed" class="head-line"></view>
			</view>

			<view class="titles">
				<view class="titles-text">选择日期</view>
				<view class="titles-choose">
					已选：
					<text>{{ selectTime }}</text>
				</view>
			</view>
			<view class="date-head">
				<view class="month-index" v-if="monthList.length">
					{{ scrollYear }} </view>
				<view class="weeks">
					<view class="weeks-item" v-for="data in weekList" :key="data">{{ data }}</view>
				</view>
			</view>
			<scroll-view :refresher-enabled="true" :refresher-triggered="navLoading" @refresherrefresh="scrollTop"
				:enable-passive="true" :enhanced="true" :bounces="false" :scroll-top="scrollTopNum"
				@scroll="scrollEvent" :scroll-anchoring="true" @scrolltolower="scrollDown" :scroll-y="true"
				class="time_select-container">
				<!-- <view class="loading" v-if="loading">加载中...</view> -->
				<view class="month-item" :id="monthdata.key" v-for="monthdata in monthList" :key="monthdata.key">
					<view class="month-index">{{
						monthdata.year
					}}年{{ monthdata.month > 9 ? monthdata.month : '0' + monthdata.month }}月</view>
					<view class="date-list">
						<view v-for="(data, index) in monthdata.months" :key="index"
							style="width:100%;justify-content: space-between; display: flex; margin: 0 0 6rpx 0; ">
							<view v-for="(item, idx) of data" :key="idx"
								:class="include(monthdata.year, monthdata.month, item.date) ? 'date-column-include' : 'date-column'"
								@click="select(item, monthdata.year, monthdata.month)">
								<!-- <view class="left"></view> -->
								<view class="right" v-if="show && isActive(item.date, monthdata.year, monthdata.month)"
									:style="['right: 0;', 'left:0;'][showBorder(item.date, monthdata.year, monthdata.month)]">
								</view>
								<view
									:class="isActive(item.date, monthdata.year, monthdata.month) ? 'date-column-active-date' : 'date-column-date'"
									:style="item.outToday && beforeToday ? 'color:#ccc' : ''">
									<text :style="item.today ? 'color:#ff5500' : ''">{{ item.date }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="loading" :style="loading?'':'color:#fff'">加载中...</view>
			</scroll-view>
			<view class="btns">
				<view class="btns-item" @click="confirm()">
					<view>确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import { formatTime } from '@/utils/utils.js';
export default {
	props: {
		loadMonth: {
			type: Number,
			default: 3
		},
		// 是否可以选择今天以后的值
		beforeToday: {
			type: Boolean,
			default: false
		},
		name: String,
		defTime: {
			type: Array,
			default: ()=>[]
		},
		// 是否可以选择今天
		isChooseToday: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			scrollYear: '',
			scrollIndex: 0,
			navLoading:false,
			loading: false,
			selectTime: '',
			weekList: ['一', '二', '三', '四', '五', '六', '日'],
			Month: [],
			dateList: [],
			time: [],
			month: 0,
			year: 0,
			show: false,
			nowData: {
				year: 0,
				month: 0,
				day: 0
			},
			monthList: [],
			scrollTopNum: 0,
			scrollFlag: true
		};
	},
	watch: {
		scrollTopNum() {
			console.log('watch-scrollTopNum', this.scrollTopNum);
		}
	},
	components: {
		uniPopup
	},
	mounted() {
		this.initDate();
	},
	methods: {

		scrollEvent(res) {
			let scrollTopNum = res.detail.scrollTop + 100;
			// console.log('watch-scrollTopNum',scrollTopNum)
			// let idx = Number(this.scrollTopNum / 270).toFixed(0)
			// console.log(scrollTopNum)
			for (let i = 0; i < this.monthList.length; i++) {
				scrollTopNum = scrollTopNum - this.monthList[i].height;
				if (scrollTopNum <= 0 || i == this.monthList.length - 1) {
					this.scrollIndex = i;
					this.scrollYear = this.monthList[this.scrollIndex].year + '年' + this.monthList[this.scrollIndex].month + '月';
					break;
				}
			}
			// this.scrollFlag = true
		},
		// 触顶
		scrollTop() {
			if (this.navLoading || this.monthList.length == 0) {
				return;
			}
			this.navLoading = true;
			console.log('触顶');
			this.addMonthList(this.monthList[0].year - 1, -1);
		},
		// 触底
		scrollDown() {
			if (this.loading  ) {
				return;
			}
			console.log('触底', this.monthList);

			this.loading = true;
			this.$nextTick(() => {
				this.addMonthList(Number(this.monthList[this.monthList.length - 1].year) + 1, 1);
			});
		},
		isActive(val, year, month) {
			if (val != '') {
				let date = new Date(year + '/' + month + '/' + val);
				if (this.time.length == 2) {
					// return this.time.indexOf(date.getTime())
					this.show = true;
				}
				return this.time.indexOf(date.getTime()) != -1;
			}
			return false;
		},
		showBorder(val, year, month) {
			let date = new Date(year + '/' + month + '/' + val);
			return this.time.indexOf(date.getTime());
		},
		// 加载月份分页  lag: 0(初始化)  1（上一页） -1(下一页)
		loadMonthFuc(lag) {
			// console.log('loadMonthFuc lag: 0(初始化)  1（上一页） -1(下一页)', lag)
	
			let num = this.loadMonth;
			if (lag == 0) {
				this.scrollTopNum = 0;
				// 初始化
				let now = new Date();
				let y = now.getFullYear();
				let m = now.getMonth() + 1;
				let list = [];
				let top = 0;

				for (let i = 1 - num; i <= 0; i++) {
					let ms = (m + i < 1 ? m + 12 + i : m + i);
					let its = {
						key: 'id' + (m + i < 1 ? y - 1 : y) + '' + (ms >= 10 ? ms : '0' + '' + ms),
						year: (m + i < 1 ? y - 1 : y),
						month: ms,
						months: this.getDate((m + i < 1 ? y - 1 : y), ms)
					};
					its.height = its.months.length * 43 + 7 + 20 + 20;
					if (i != 0) {
						top = top + its.height;
					}

					list.push(its);
				}
				let its = {
					key: 'id' + (m + 1 > 12 ? y + 1 : y) + '' + (m + 1 > 12 ? m - 12 + 1 : m + 1),
					year: (m + 1 > 12 ? y + 1 : y),
					month: (m + 1 > 12 ? m - 12 + 1 : m + 1),
					months: this.getDate((m + 1 > 12 ? y + 1 : y), (m + 1 > 12 ? m - 12 + 1 : m + 1))
				};
				its.height = its.months.length * 43 + 7 + 20 + 20;
				list.push(its);

				this.monthList = list;
				this.$nextTick(() => {
					this.scrollTopNum = top - 60;
					// console.log('scrollTopNum lag == 0', top)
					this.loading = false;
					this.navLoading = false;
				});
				return;
			} else if (lag > 0) {
				// 下一页
				let y = this.monthList[this.monthList.length - 1].year;
				let m = this.monthList[this.monthList.length - 1].month;
				let list = [];
				for (let i = 1; i <= num; i++) {
					let its = {
						key: 'id' + (m + i > 12 ? y + 1 : y) + '' + (m + i > 12 ? m - 12 + i : m + i),
						year: (m + i > 12 ? y + 1 : y),
						month: (m + i > 12 ? m - 12 + i : m + i),
						months: this.getDate((m + i > 12 ? y + 1 : y), (m + i > 12 ? m - 12 + i : m + i))
					};
					its.height = its.months.length * 43 + 7 + 20 + 20;
					list.push(its);
				}
				this.monthList.push(...list);
				this.loading = false;
				return;
			} else if (lag < 0) {
				this.scrollTopNum = 0;
				// 上一页 
				let y = this.monthList[0].year;
				let m = this.monthList[0].month;
				let top = 0;
				let list = [];
				for (let i = 0 - num; i < 0; i++) {
					let ms = (m + i < 1 ? m + 12 + i : m + i);
					let its = {
						key: 'id' + (m + i < 1 ? y - 1 : y) + '' + (ms >= 10 ? ms : '0' + '' + ms),
						year: (m + i < 1 ? y - 1 : y),
						month: ms,
						months: this.getDate((m + i < 1 ? y - 1 : y), ms)
					};
					its.height = its.months.length * 43 + 7 + 20 + 20;
					top = top + its.height;
					list.push(its);
				}
				this.monthList.unshift(...list);
				this.$nextTick(() => {
					this.scrollTopNum = top;
					// console.log('scrollTopNum', top)
					this.navLoading = false;
				});
				return;
			}
			// console.log('this.monthList', this.monthList)
			this.loading = false;
		},
		// 获取月份数组
		addMonthList(year, yearIndex) {
			console.log('/获取月份数组');
			this.loadMonthFuc(yearIndex);
			return;
		},

		// 计算每个月的天数以及显示
		getDate(year, month) {
			let week = [];
			let Month = [];
			var nowDate = new Date(year, month, 0);

			let currentYear = nowDate.getFullYear();
			let nextYear = nowDate.getFullYear() + 1;
			let lastYear = nowDate.getFullYear() - 1;

			let nextDate = new Date(currentYear, nowDate.getMonth() + 1, 0);
			let oldDate = new Date(currentYear, nowDate.getMonth(), 0);

			if (nowDate.getMonth() == 1) {
				nextDate = new Date(currentYear, nowDate.getMonth() + 1, 0);
				oldDate = new Date(lastYear, 11, 0);
			} else if (nowDate.getMonth() == 12) {
				nextDate = new Date(nextYear, 0, 0);
				oldDate = new Date(currentYear, nowDate.getMonth(), 0);
			}

			let lastMonthDay = oldDate.getDate();

			let totalDays = nowDate.getDate();

			let monthHead = new Date(nowDate.setDate(1)).getDay() - 1 == -1 ? 6 : new Date(nowDate.setDate(1)).getDay() - 1;
			let monthTail = 7 - new Date(nowDate.setDate(totalDays)).getDay();
			// let monthDays=date.getDate()
			//
			for (let count = 1; count <= 7; count++) {
				if (monthHead > 0) {
					week.push({
						date: '',
						currentMonth: false
					});
					monthHead--;
				} else {
					break;
				}
			}
			const addzero = num => {
				return num > 9 ? num : '0' + '' + num;
			};
			const today = this.nowData.year + '' + addzero(this.nowData.month);
			for (let count = 1; totalDays >= count; count++) {
				let out = false;
				if (this.isChooseToday) {
					// 可选今天
					if (year + '' + addzero(month) > today) {
						out = true;
					}
					if (year + '' + addzero(month) == today && this.nowData.day < count) {
						out = true;
					}
				} else {
					// 不选今天
					if (year + '' + addzero(month) > today) {
						out = true;
					}
					if (year + '' + addzero(month) == today && this.nowData.day <= count) {
						out = true;
					}
				}

				week.push({
					date: count,
					currentMonth: true,
					outToday: out, // 是否大于等于今天
					today: year == this.nowData.year && month == this.nowData.month && count == this.nowData.day ? true : false
				});
				if (week.length == 7) {
					Month.push(week);
					week = [];
				}
			}
			if (monthTail != 7) {
				for (let count = 1; count <= 7; count++) {
					if (monthTail > 0) {
						week.push({
							date: '',
							currentMonth: false
						});
						monthTail--;
						if (week.length == 7) {
							Month.push(week);
							week = [];
						}
					} else {
						break;
					}
				}
			}
			nowDate = null;
			oldDate = null;
			nextDate = null;
			monthHead = null;
			monthTail = null;
			// this.Month=Month
			return Month;

			// console.log(this.Month);
		},
		// 控制选择逻辑
		select(item, year, month) {
			// console.log('select', item.date, year, month);
			const addzero = num => {
				return num > 9 ? num : '0' + '' + num;
			};
			const today = this.nowData.year + '' + addzero(this.nowData.month);
			let out = false;
			if (this.isChooseToday) {
				// 可选今天
				if (year + '' + addzero(month) > today) {
					out = true;
				}
				if (year + '' + addzero(month) == today && this.nowData.day < item.date) {
					out = true;
				}
			} else {
				// 不选今天
				if (year + '' + addzero(month) > today) {
					out = true;
				}
				if (year + '' + addzero(month) == today && this.nowData.day <= item.date) {
					out = true;
				}
			}
			// console.log('select', out, today, item, this.nowData.year);
			let val = item.date;
			// console.log(item, 6666,this.include( year, month,item.date));
			if (item.today && this.name && this.name.indexOf('achievements') != -1) {
				uni.showToast({
					title: '绩效统计不包括今日~',
					icon: 'none'
				});
				return;
			}
			if (item.outToday && this.beforeToday) {
				uni.showToast({
					title: '请选择今天以前的日期',
					icon: 'none'
				});

				return;
			}
			// 以下支持跨月
			if (val != 0) {
				let date = new Date(year + '/' + month + '/' + val);

				if (this.time.length < 2) {
					if (this.time.indexOf(date.getTime()) == -1) {
						this.time.push(date.getTime());
					}
					this.time.sort((a, b) => {
						return a - b;
					});
				} else {
					this.time = [];
					this.time.push(date.getTime());
				}

				if (this.time.length > 0) {
					let firstTime = formatTime(this.time[0], '.');
					if (this.time.length == 1) {
						this.selectTime = firstTime;
					} else {
						let endTime = formatTime(this.time[1], '.');
						this.selectTime = firstTime + '-' + endTime;
					}
				} else {
					this.selectTime = '';
					this.show = false;
				}
			}
		},
		// 渲染日期之间的天数格子
		include(year, month, val) {
			if (this.time.length == 2 && val != '') {
				let date = new Date(year + '/' + (month > 9 ? month : '0' + month) + '/' + val).getTime();

				return date > this.time[0] && date < this.time[1];
			}

			return false;
		},
		// 初始化，默认为当前年月
		initDate() {
			let month = new Date().getMonth() + 1;
			let year = new Date().getFullYear();
			let day = new Date().getDate();
			this.monthList = [];
			this.month = month;
			this.year = year;
			this.nowData.month = month;
			this.nowData.year = year;
			this.nowData.day = day;
			// this.getDate(year, month);
			this.loading = true;
			console.log('initDate');
			this.addMonthList(year, 0);

			if (this.defTime && this.defTime.length) {
				let arr = [];
				for (var i = 0; i < this.defTime.length; i++) {
					arr.push(new Date(this.defTime[i].replace(/-/g, '/')).getTime());
				}
				this.time = arr;
			}
		},

		confirm() {
			if (!this.selectTime) {
				uni.showToast({
					icon: 'none',
					title: '请选择日期'
				});
			} else {
				if (this.time.length == 2) {
					let differDay = Math.abs(new Date(this.time[0]) - new Date(this.time[1])) / 1000 / 60 / 60 / 24;
					// console.log(differDay,'differDay')
					if (differDay > 90) {
						uni.showToast({
							icon: 'none',
							title: '日期选择不能大于90天'
						});
						return;
					}
				}
				// console.log(this.selectTime,'this.selectTime')
				this.$emit('close', this.selectTime);
			}
		},
		cancel() {
			this.$emit('close');
			// this.$emit('cancle')
		}
	}
};
</script>

<style lang="scss" scoped>
@keyframes eject {
	0% {
		transform: translateY(1040rpx);
	}

	100% {
		transform: translateY(0);
	}
}

@mixin midPosition {
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	margin: auto;
}

@mixin column {
	width: 80rpx;
	height: 80rpx;
	display: flex;
	position: relative;
	padding: 0 7rpx;
}

@mixin footer {
	width: 50%;
	height: 73rpx;
	font-size: 28rpx;
	align-items: center;
	font-family: PingFangSC, PingFangSC-Regular;
	font-weight: bold;
	text-align: center;
	line-height: 40rpx;
	position: relative;
}

.img {
	width: 36rpx;
	height: 36rpx;
}

.flex-view {
	display: flex;
	height: fit-content;
	width: fit-content;
}

.mask {
	width: 100%;
	height: 100%;
	// @include midPosition background: rgba(0, 0, 0, 0.4);
	background: rgba(0, 0, 0, 0.17);
	position: fixed;
	top: 0;
	left: 0;
	z-index: 300;
}

.time_select {
	width: 750rpx;
	height: 1040rpx;
	animation: eject 0.3s;
	background: #ffffff;
	border-radius: 8rpx 8rpx 0rpx 0rpx;
	box-shadow: 0rpx -4rpx 12rpx 0rpx rgba(0, 0, 0, 0.12);
	position: fixed;
	bottom: 0rpx;
	left: 0rpx;
	z-index: 99;

	&-head {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx 0;

		.head-line {
			width: 64rpx;
			height: 10rpx;
			background: #d8d8d8;
			border-radius: 6rpx;
		}
	}

	&-body {
		display: flex;
		justify-content: space-around;
		width: 100%;
		height: 68rpx;
		background: #f5fbff;
		margin: auto;
		align-items: center;

		view {
			color: #0091ff;
			font-weight: bold;
		}
	}

	&-container {
		width: 100%;
		height: calc(100% - 150rpx - 90rpx - 130rpx);
	}
}

.titles {
	width: calc(100% - 80rpx);
	padding: 0 40rpx;
	height: 90rpx;

	&-text {
		color: #333333;
		font-size: 32rpx;
		font-weight: bold;
		padding-bottom: 8rpx;
	}

	&-choose {
		font-size: 28rpx;
		color: #666;

		text {
			color: #333333;
		}
	}
}

.month-index {
	color: #333333;
	font-size: 30rpx;
	font-weight: bold;
	text-align: center;
	height: 40rpx;
	line-height: 40rpx;
}

.month-item {
	width: 100%;
	display: flex;
	padding: 20rpx 0;
	align-items: center;
	justify-content: center;
	flex-direction: column;

	.date-list {
		width: calc(100% - 40rpx);
		padding-top: 15rpx;
	}
}

.date-head {
	width: 100%;
	height: 100rpx;
	display: flex;
	flex-direction: column;
	justify-content: flex-end;

	.weeks {
		width: calc(100% - 40rpx);
		padding: 0 20rpx;
		box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(162, 162, 162, 0.19);
		display: flex;
		justify-content: space-around;
		font-size: 24rpx;
		font-weight: 400;
		text-align: center;
		color: #999999;

		&-item {
			flex: 1;
			padding: 10rpx 0;
		}
	}
}

.date-column {
	flex: 1;

	@include column &-date {
		@include midPosition width: fit-content;
		height: fit-content;
	}

	&-active {
		@include column background: #def1ff;

		&-date {
			// @include midPosition
			border-radius: 50rpx;
			background: #0091ff;
			color: #ffffff;
			width: 80rpx;
			height: 80rpx;
			position: absolute;
			top: 0;

			text {
				width: fit-content;
				height: fit-content;
				@include midPosition;
			}
		}
	}

	&-include {
		flex: 1;
		width: 80rpx;
		height: 80rpx;
		position: relative;
		padding: 0 7rpx;
		background: #def1ff;

		&-date {
			@include midPosition;
			width: fit-content;
			height: fit-content;
		}
	}
}

.loading {
	text-align: center;
	color: #999;
	height: 36rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	padding: 15rpx 0;
	transition: .1s all;

}

.right {
	width: 50%;
	height: 100%;
	position: absolute;
	background: #def1ff;
}

.btns {
	width: 750rpx;
	height: 128rpx;
	background: #ffffff;
	border-top: 2rpx solid rgba(0, 0, 0, 0.19);
	display: flex;
	align-items: center;
	justify-content: center;

	&-item {
		width: 670rpx;
		height: 70rpx;
		background: #f5fbff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #0091ff;
		border-radius: 0rpx 8rpx 8rpx 0rpx;
	}

	&-item:last-child {
		background-color: #0091ff;
		color: #fff;
		border-radius: 0rpx 8rpx 8rpx 0rpx;
	}
}
</style>
